package org.pearl.thread.demo.test001;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by TD on 2021/4/12
 * 自定义线程池： 模拟车站卖票
 * 1.活动窗口为CPU核心线程数
 * 2.最大20个窗口同时卖票
 * 3.人数不多时，空间的窗口等待10秒，没人则会休息
 * 4.等待座位10个
 * 5.等待座位满了以后，开启一个Main窗口去卖票
 */
public class ThreadPoolExecutorTest001 {

    public static void main(String[] args) {
        // 卖出的票数
        int tickets = 0;
        // 总人数
        int people = 1000;
        // cpu核心线程数
        int cpuNum = Runtime.getRuntime().availableProcessors();
        System.out.println("当前开启活动窗口:" + cpuNum);
        LinkedBlockingDeque<Runnable> linkedBlockingDeque = new LinkedBlockingDeque<>(10);
        // 创建卖票Executor
        ThreadPoolExecutor executor = new ThreadPoolExecutor(cpuNum,
                20,
                10,
                TimeUnit.SECONDS,
                linkedBlockingDeque,
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
        //开启卖票
        try {
            for (int i = 0; i < people; i++) {
                executor.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "窗口正在卖票");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            executor.shutdown();
        }
    }
}
